<template>
  <section>
    <!--工具条-->
    <el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
      <el-form :inline="true" :model="filters" class="demo-form-inline">
        <el-form-item label="模版名称">
          <el-input v-model="filters.keyword" placeholder="请输入模版名称"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" v-on:click="queryBaran">查询</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="show(0)">新增</el-button>
        </el-form-item>
      </el-form>
    </el-col>

    <!--列表-->
    <el-table :data="templates" highlight-current-row v-loading="listLoading" @selection-change="selsChange" style="width: 100%;">
      <el-table-column type="selection" width="55">
      </el-table-column>
      <el-table-column type="index" width="60">
      </el-table-column>
      <el-table-column prop="id" label="模版ID" width="100" sortable>
      </el-table-column>
      <el-table-column prop="name" label="模版名称" width="160" sortable>
      </el-table-column>
      <el-table-column prop="brandIds" label="关联品牌" width="560" sortable>
      </el-table-column>
      <el-table-column prop="specIds" label="关联模版" width="160" sortable>
      </el-table-column>
      <el-table-column prop="customAttributeItems" label="扩展属性" width="160" sortable>
        <template scope="scope">
          <span v-for="TemplateView in JSON.parse(scope.row.customAttributeItems)">{{TemplateView.text}},</span>
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template scope="scope">
          <el-button size="small" @click="show(scope.row)">编辑</el-button>
          <el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!--工具条-->
    <el-col :span="24" class="toolbar">
      <el-button type="danger" :disabled="this.sels.length===0" @click="batchRemove">批量删除</el-button>
      <el-pagination layout="prev, pager, next" :current-page="pageNum" @current-change="handleCurrentChange" :page-size="pageSize" :total="total" style="float:right;">
      </el-pagination>
    </el-col>

    <!--编辑界面-->
    <el-dialog :title="title" width="600px" :visible.sync="editFormVisible" :close-on-click-modal="false">
      <el-form :model="showTemplate" label-width="80px" :rules="editFormRules" ref="editForm">
        <el-form-item label="商品类型" prop="name">
          <el-input v-model="showTemplate.name" auto-complete="off"></el-input>
        </el-form-item>
      </el-form>
      <el-form :model="showTemplate" label-width="80px" :rules="editFormRules" ref="editForm">
        <el-form-item label="关联品牌" prop="brandIds">
          <el-select v-model="showTemplate.brandIds" multiple placeholder="请选择">
            <el-option
                v-for="item in brands"
                :key="item.id"
                :label="item.name"
                :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <el-form :model="showTemplate" label-width="80px" :rules="editFormRules" ref="editForm">
        <el-form-item label="关联规格" prop="specIds">
          <el-select v-model="showTemplate.specIds" multiple placeholder="请选择">
            <el-option
                v-for="item in specs"
                :key="item.id"
                :label="item.specName"
                :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div>
        <el-button @click="addForm">新建扩展属性</el-button>
      </div>
      <el-table
          :data="showTemplate.customAttributeItems"
          style="width: 100%"
          max-height="250">
        <el-table-column
            fixed
            prop="text"
            label="属性名称"
            width="450">
          <template slot-scope="scope">
            <el-input v-model="scope.row.text"></el-input>
          </template>
        </el-table-column>
        <el-table-column
            label="操作"
            width="150">
          <template slot-scope="scope">
            <el-button
                @click="deleteRow(scope.$index, tableData)"
                size="small">
              移除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="editFormVisible = false">取消</el-button>
        <el-button type="primary" @click.native="editSubmit" :loading="editLoading">提交</el-button>
      </div>
    </el-dialog>

  </section>
</template>

<script>
import axios from "axios";

export default {
  data() {
    return {
      //表单回显
      showTemplate: {
        id:null,
        name:"",
        brandIds:[
          {
            name:"",
            id:null
          }
        ],
        specIds:[],
        customAttributeItems:[
        ]},
      ids: [],
      title: '',
      filters: {
        keyword: ''
      },
      templates: [],
      brands: [],
      specs: [],
      template:{

      },
      total: 0,
      pageNum: 1,
      pageSize:5,
      listLoading: false,
      sels: [],//列表选中列
      editFormVisible: false,//编辑界面是否显示
      editLoading: false,
      editFormRules: {
        name: [
          { required: true, message: '请输入姓名', trigger: 'blur' }
        ]
      },

    }
  },
  methods: {
    //删除表单
    deleteRow(index) {
      this.showTemplate.customAttributeItems.splice(index);
    },
    //增加表单
    addForm() {
      var o = {};
      this.showTemplate.customAttributeItems.push(o);
    },
    //获取规格列表
    queryAllSpec() {
      axios.get("/spec/queryAllSpec").then(resp=>{
        // console.log(resp.data.data);
        this.specs = resp.data.data;
      }).catch(resp=>{

      })
    },
    //获取品牌列表
    queryAllBrand() {
      axios.get("/brand/queryAllBrand").then(resp=>{
        // console.log(resp.data.data);
        this.brands = resp.data.data;
      }).catch(resp=>{

      })
    },
    //获取模版列表
    queryBaran(){
      // 准备参数
      let params = {
        pageSize: this.pageSize, //页面大小
        pageNum: this.pageNum,   //页码
        trimParam:{
          name:this.filters.keyword
        }
      }
      //页面展示
      this.$http.post("/template/queryPage",params)
          .then(resp=>{
            // console.log(resp);
            this.templates = resp.data.data.list;
            this.total = resp.data.data.total;
          }).catch(resp=>{
        alert("网络异常，稍后重试");
      })
    },
    //删除
    handleDel: function (index, row) {
      // console.log(row);
      this.$confirm('确认删除该记录吗?', '温馨提示', {
        type: 'warning'
      }).then(() => {
        this.listLoading = true;
        this.$http.delete("/template/deleteInfo/"+row.id)
            .then(resp=>{
                  //去除忙等框
                  if (resp.data.code==="1") {
                    this.editFormVisible = false;
                    this.$message({
                      message: '删除成功',
                      type: 'success'
                    });
                    this.listLoading = false;
                    this.queryBaran();
                  }
                }

            )
            .catch(result=>{
              //去除忙等框
              this.listLoading = false;
              //提示
              this.$message({
                message: '系统错误！',
                type: 'error'
              });
            })

      }).catch(() => {

      });
    },
    //显示编辑界面
    show (row) {
      console.log(row);
      this.editFormVisible = true;
      if (row === 0) {
        this.showTemplate={
          id:null,
          name:"",
          brandIds:[],
          specIds:[],
          customAttributeItems:[
          ]
        }
        this.title = "新增";
      } else {
        this.title = "编辑";
      }
      if (row !== 0) {
        this.showTemplate.id = row.id;
        this.showTemplate.name = row.name;
        axios.get("/template/queryById/"+row.id).then(resp=>{
          console.log(resp);
          //回显品牌数据
          var bids = [];
          JSON.parse(resp.data.data.brandIds).map(brand=>{
            bids.push(brand.id);
          })
          this.showTemplate.brandIds = bids;
          //回显规格数据
          var sids = [];
          JSON.parse(resp.data.data.specIds).map(spec=>{
            sids.push(spec.id);
          })
          this.showTemplate.specIds = sids;
          //回显扩展属性
          var cusName = [];
          JSON.parse(resp.data.data.customAttributeItems).map(cus => {
            cusName.push(cus);
          });
          console.log(cusName);
          this.showTemplate.customAttributeItems = cusName;
        }).catch(resp=>{
        });
      }
    },
    //提交表单
    editSubmit: function () {
      console.log(this.showTemplate);
      this.$confirm('确认提交吗？', '提示', {}).then(() => {
        this.editLoading = true;
        // NProgress.start();
        var brandIds = JSON.stringify(this.showTemplate.brandIds);
        var specIds = JSON.stringify(this.showTemplate.specIds);
        var customAttributeItems = JSON.stringify(this.showTemplate.customAttributeItems);
        var vo = {};
        vo.brandIds = brandIds;
        vo.specIds = specIds;
        vo.customAttributeItems = customAttributeItems;
        vo.id = this.showTemplate.id;
        vo.name = this.showTemplate.name;
        axios.post("/template/save", vo).then(resp => {
          console.log(resp);
          if (resp.data.code === "1") {
            this.editFormVisible = false;
            this.$message({
              message: '保存成功',
              type: 'success'
            });
            this.editLoading = false;
            this.queryBaran();
          }
        }).catch(resp => {

        })
      });
    },
    handleCurrentChange(val) {
      this.pageNum = val;
      this.queryBaran();
    },

    selsChange: function (sels) {
      // console.log(sels);
      this.sels = sels;
    },
    //批量删除
    batchRemove: function () {
      // var ids = this.sels.map(item => item.id).toString();
      this.sels.forEach(item => this.ids.push(item.id));
      console.log(this.ids);
      this.$confirm('确认删除选中记录吗？', '提示', {
        type: 'warning'
      }).then(() => {
        this.listLoading = true;
        //NProgress.start();
        // let para = { ids: ids };
        this.$http.patch("/template/deleteBatch",this.ids).then((resp) => {
          if (resp.data.code==="1") {
            this.$message({
              message: '批量删除成功',
              type: 'success'
            });
            this.listLoading = false;
            this.queryBaran();
          }
        });
      }).catch(() => {

      });
    }
  },
  mounted() {
    this.queryBaran();
    this.queryAllBrand();
    this.queryAllSpec();
  }
}

</script>

<style scoped>

</style>